package main

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/pflag"
	"github.com/spf13/viper"

	"devfans.com/component/internal/options"
)

func main() {
	fmt.Println("Viper Demo Running....")
	// fmt.Println(time.Now().String())

	// initFromYaml()
	initStructFromYaml()
	// initFromCmd()
	// initFromEnv()
}

func initFromYaml() {
	viper.SetConfigName("app-service")
	viper.SetConfigType("yaml")
	// viper.SetConfigType("json")
	viper.AddConfigPath("./configs/")
	// 可添加多个路径
	viper.AddConfigPath("../.././configs/")
	if err := viper.ReadInConfig(); err != nil {
		fmt.Println("read config failed:%v", err)
	}

	viper.WatchConfig()
	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config file changed:", e.Name)
	})

	fmt.Println("server.host", viper.Get("server.host"))
	fmt.Println("server.port", viper.Get("server.port"))
	fmt.Println("mysql.host", viper.Get("mysql.host"))
	fmt.Println("mysql.port", viper.Get("mysql.port"))
	fmt.Println("mysql.database", viper.Get("mysql.database"))
	fmt.Println("mysql.username", viper.Get("mysql.username"))
	fmt.Println("mysql.password", viper.Get("mysql.password"))

	// time.Sleep(time.Second * 10)
}

func initStructFromYaml() {
	viper.SetConfigName("app-service")
	viper.SetConfigType("yaml")
	// viper.SetConfigType("json")
	viper.AddConfigPath("./configs")
	// 可添加多个路径
	viper.AddConfigPath("../../configs")
	if err := viper.ReadInConfig(); err != nil {
		fmt.Println("read config failed:%v", err)
	}
	fmt.Println("server.host", viper.Get("server.host"))

	var serverOption options.ServerOption
	fmt.Println("default option", serverOption)
	// viper.Unmarshal(&serverOption)
	viper.UnmarshalKey("server", &serverOption)
	fmt.Println("server option", serverOption)

	// time.Sleep(time.Second * 10)
}

// initFromCmd 绑定命令行
func initFromCmd() {

	pflag.Int("redis.port", 1234, "redis port option, value is int")

	pflag.Parse()
	viper.BindPFlags(pflag.CommandLine)

	i := viper.GetInt("redis.port") // 通过viper从pflag中获取值

	fmt.Println("redis port: ", i)
}

// initFromEnv 绑定环境变量
func initFromEnv() {
	viper.AutomaticEnv()
	viper.BindEnv("devfans", "devfans")
	fmt.Println("devfans: ", viper.Get("devfans"))

	viper.SetEnvPrefix("dev") //将自动大写
	viper.BindEnv("host")
	host := viper.Get("host")
	fmt.Println("dev host: ", host)

	// os.Setenv("SPF_ID", "13") // 通常在应用以外完成
}
